package cn.shujuhai.qtadmin.platform.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.jetbrains.annotations.NotNull;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.shujuhai.qtadmin.platform.domain.Role;
import cn.shujuhai.qtadmin.platform.domain.RolePermission;
import cn.shujuhai.qtadmin.platform.domain.UserRole;
import cn.shujuhai.qtadmin.platform.pluging.logging.BusinessType;
import cn.shujuhai.qtadmin.platform.pluging.logging.Logging;
import cn.shujuhai.qtadmin.platform.pluging.result.Result;
import cn.shujuhai.qtadmin.platform.service.RolePermissionService;
import cn.shujuhai.qtadmin.platform.service.RoleService;

/**
 * 用户API
 *
 * @author dch798
 * @date 2021/08/21 22:13
 **/
@RestController
@RequestMapping("admin/role")
public class AdminRoleController {

    public static final String ROLE_ID = "role_id";
    public static final String CODE = "code";

    final RoleService roleService;
    final RolePermissionService rolePermissionService;

    public AdminRoleController(RolePermissionService rolePermissionService, RoleService roleService) {
        this.rolePermissionService = rolePermissionService;
        this.roleService = roleService;
    }

    /**
     *
     * @param page
     *            当前页
     * @return 角色列表
     */
    @PostMapping("roleList")
    @Logging(title = "角色列表", describe = "角色列表", type = BusinessType.QUERY)
    public Result roleList(int page, int limit, @NotNull Role role) {
        PageMethod.startPage(page == 0 ? 1 : page, limit == 0 ? 15 : limit);
        var queryWrapper = new QueryWrapper<Role>();
        if (CharSequenceUtil.isNotBlank(role.getCode())) {
            queryWrapper.like(CODE, role.getCode());
        }
        if (CharSequenceUtil.isNotBlank(role.getName())) {
            queryWrapper.like("name", role.getName());
        }
        var roleList = role.selectList(queryWrapper);
        return Result.success("获取成功", new PageInfo<>(roleList));
    }

    /**
     * 
     * @param id
     *            id
     * @return result
     */
    @PostMapping("roleDelete")
    @Transactional(rollbackFor = Exception.class)
    @Logging(title = "角色删除", describe = "角色删除", type = BusinessType.REMOVE)
    public Result roleDelete(Long id) {
        var ids = new ArrayList<Long>();
        ids.add(id);
        var allRoles = this.roleService.list();
        this.getChildrenRoles(id, allRoles, ids);
        if (new UserRole().selectCount(new QueryWrapper<UserRole>().in(ROLE_ID, ids)) <= 0) {
            this.roleService.removeByIds(ids);
            this.rolePermissionService.remove(new QueryWrapper<RolePermission>().in(ROLE_ID, ids));
            return Result.success("删除成功");
        }
        return Result.failure("该角色已经分配给用户，删除失败");
    }

    /**
     *
     * @param id
     *            id
     * @param allRoles
     *            allRoles
     * @param ids
     *            ids
     */
    private void getChildrenRoles(Long id, @NotNull List<Role> allRoles, List<Long> ids) {
        var childrens = allRoles.stream().filter(s -> s.getParentId().equals(id)).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(childrens)) {
            childrens.forEach(x -> {
                ids.add(x.getId());
                this.getChildrenRoles(x.getId(), allRoles, ids);
            });
        }
    }

    /**
     *
     * @param role
     *            角色信息
     * @return 新增角色结果
     */
    @PostMapping("roleAdd")
    @Transactional(rollbackFor = Exception.class)
    @Logging(title = "新增角色", describe = "新增角色", type = BusinessType.ADD)
    public Result roleAdd(Role role) {
        if (role.selectCount(new QueryWrapper<Role>().eq(CODE, CharSequenceUtil.trim(role.getCode()))) > 0) {
            return Result.failure("该角色已经存在");
        }
        if (role.insert() && ObjectUtil.isNotEmpty(role.getAuthids())) {
            var roleAuths = new ArrayList<RolePermission>();
            for (Long authid : role.getAuthids()) {
                var roleAuth = new RolePermission();
                roleAuth.setRoleId(role.getId());
                roleAuth.setPermissionId(authid);
                roleAuths.add(roleAuth);
            }
            this.rolePermissionService.saveBatch(roleAuths);
        }
        return Result.success("新增成功");
    }

    /**
     *
     * @param role
     *            角色信息
     * @return 修改角色结果
     */
    @PostMapping("roleUpdate")
    @Transactional(rollbackFor = Exception.class)
    @Logging(title = "修改角色", describe = "修改角色", type = BusinessType.EDIT)
    public Result roleUpdate(@NotNull Role role) {
        if (role.updateById() && ObjectUtil.isNotEmpty(role.getAuthids())) {
            var roleAuths = new ArrayList<RolePermission>();
            for (Long authid : role.getAuthids()) {
                var roleAuth = new RolePermission();
                roleAuth.setRoleId(role.getId());
                roleAuth.setPermissionId(authid);
                roleAuths.add(roleAuth);
            }
            this.rolePermissionService.remove(new QueryWrapper<RolePermission>().eq(ROLE_ID, role.getId()));
            this.rolePermissionService.saveBatch(roleAuths);
        }
        return Result.success("修改成功");
    }

    /**
     *
     * 角色信息
     * 
     * @return 修改角色结果
     */
    @PostMapping("roles")
    @Logging(title = "角色列表", describe = "角色列表", type = BusinessType.QUERY)
    public Result roles() {
        return Result.success("获取成功", new Role().selectAll());
    }
}
